package com.bins.oauth2.security;

import com.bins.oauth2.service.UserService;
import com.bins.oauth2.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String passwd = "";
        if (UserUtils.isEmail(username)) {
            passwd = userService.selectPasswordByEmail(username);
        } else if (UserUtils.isPhone(username)) {
            passwd = userService.selectPasswordByPhone(username);
        } else {
            throw new RuntimeException("登录账号不存在");
        }
        return new User(username, passwd, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    }
}
